package fun.codedesign.principle.advice151.a124;

import org.junit.Test;

import fun.codedesign.principle.advice151.Good;

import java.util.concurrent.*;

/**
 * 使用回调接口 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-09 20:42
 * @since 1.0.0
 */
@Good("异步回调的时候考虑使用Callable接口")
public class UseCallable {

    // 建议124： 异步运算考虑使用Callable接口
    @Test
    public void test124() throws Exception {
        // 单线程异步执行器
        ExecutorService es = Executors.newSingleThreadExecutor();
        // 固定数量线程池
        // ExecutorService es2 = Executors.newFixedThreadPool(16);

        Future<Integer> future = es.submit(new TestCallalbe(100));
        while (!future.isDone()) {
            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println("##########");
        }
        System.out.println("计算结束，结果是：" + future.get());
    }

    class TestCallalbe implements Callable<Integer> {

        private int seedMoney;

        public TestCallalbe(int seedMoney) {
            this.seedMoney = seedMoney;
        }

        @Override
        public Integer call() throws Exception {
            TimeUnit.MILLISECONDS.sleep(5000);
            return seedMoney / 10;
        }
    }
}
